package bank_to_bank;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.logging.Logger;

import bank_access.Kommunikationsmodul;

/**
 * @author pascal
 * 
 * Handles one specific bank transfer that has been assigned to this Runnable 
 * by the TransferHandler
 */
public class TransferHandlerSkeletonTask implements Runnable {

    private Socket socket;
    private TransferHandlerImplBase xfer;
    private Logger logger;
    private String hostName;
    private DataOutputStream dataOut;

    public TransferHandlerSkeletonTask(TransferHandlerImplBase xfer, Socket socket) {
        logger = Kommunikationsmodul.getLogger();
        this.socket = socket;
        this.xfer = xfer;
    }

    @Override
    public void run() {
        try {
            BufferedReader dataIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            dataOut = new DataOutputStream(socket.getOutputStream());
            String message = dataIn.readLine();
            hostName = socket.getInetAddress().getCanonicalHostName();
            logger.info("Nachricht von " + hostName + ":" + socket.getPort() + ": " + message);

            String[] params = message.split("#");
            String command = params[1];
            //Nachricht ist z.B. "CALL#KONTOEINRICHTEN#**\n";
            if (command.equals("GUTSCHREIBEN")) {
                String kontoID = params[2];
                Double betrag = Double.valueOf(params[3]);
                if (xfer.gutschreiben(kontoID, betrag)) {
                    Thread.sleep(5000);
                    dataOut.writeBytes("OK#**\n");
                    logger.info("Nachricht an " + hostName + ":" + socket.getPort() + ": " + "OK#**\n");
                } else {
                    dataOut.writeBytes("ERROR#**\n");
                    logger.info("Nachricht an " + hostName + ":" + socket.getPort() + ": " + "ERROR#Fehler beim Einzahlen**\n");
                }
            }
        } catch (IOException e) {
            logger.info("IOException " + e);
        } catch (NoSuchAccountException e) {
            try {
                dataOut.writeBytes("ERROR#NoSuchAccount**\n");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            logger.info("Nachricht an " + hostName + ":" + socket.getPort() + ": " + "ERROR#NoSuchAccount**\n");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
